package com.foreveross.eimpc.web.service;

import com.alibaba.fastjson.JSONObject;
import com.foreveross.eimpc.web.constants.Configs;
import com.foreveross.eimpc.web.util.HttpClientUtil;
import com.foreveross.eimpc.web.util.JsonMapper;
import com.foreveross.eimpc.web.util.MD5Util;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class LoginManager {
	protected static Logger logger = LoggerFactory.getLogger(LoginManager.class);
	private static JsonMapper mapper = JsonMapper.nonEmptyMapper();
	static Map<String,String>  ipMap = new HashMap<String,String>();
	
	public static String doLogin(String username, String password,HttpServletRequest req){
		String clientip = getIpAddr(req);
		logger.debug("clientip="+clientip+":username="+username);
		String strmd = ipMap.get(clientip+username);
		if(strmd==null||"".equals(strmd)){
			strmd = new Date().getTime()+""+new Random().nextLong();
			ipMap.put(clientip+username, strmd);
		}
		Map<String,String> map = new HashMap<String,String>();
		map.put("appId", "myappId");
	
		map.put("deviceId", strmd);
		map.put("secret", "mysecret");
		map.put("username", username);
		password = MD5Util.encode(password);
		map.put("password", password);
		map.put("devicePlatform", "PcWeb");
		map.put("ssl", "true");
		map.put("encryption", "true");
		map.put("version", "1");
	//	return HttpClientUtil.post(Configs.LOGIN_URL, mapper.toJson(map), Configs.CONNECT_TIMEOUT, Configs.SOCKET_TIMEOUT);
		return HttpClientUtil.post(Configs.LOGIN_URL, mapper.toJson(map));
	}
	public static String doGrant(){
		return HttpClientUtil.get(Configs.GRANT_URL);
	}

    public static JSONObject refreshToken(String access_token) {
        logger.info(" refresh token ");
        String result = null;
        try {
            Configuration config = new PropertiesConfiguration("config.properties");
            String url = MessageFormat.format(Configs.REFRESH_TOKEN, config.getString("grant_type"), config.getString("grant_id"), config.getString("grant_secret"), access_token);
            result = HttpClientUtil.get(url);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return JSONObject.parseObject(result);
    }

	public static String getIpAddr(HttpServletRequest request) {  
	      String ip = request.getHeader("x-forwarded-for");  
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	         ip = request.getHeader("Proxy-Client-IP");  
	     }  
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	         ip = request.getHeader("WL-Proxy-Client-IP");  
	      }  
	     if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	          ip = request.getRemoteAddr();  
	     }  
	     return ip;  
    }
}
